package com.timk.goserver.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import com.timk.goserver.server.model.ServerGameInfo;
import com.timk.goserver.server.util.HibernateUtil;

/**
 * Servlet for downloading game records
 * @author TKington
 *
 */
public class DownloadGameServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int gameid = Integer.parseInt(request.getParameter("id")); 
		
		Session hbSession = HibernateUtil.startTrans();

		ServerGameInfo info = (ServerGameInfo)hbSession
				.get(ServerGameInfo.class, new Integer(gameid));
		
		hbSession.getTransaction().commit();

		if(info == null) {
			response.getWriter().println("Game id " + gameid + " does not exist");
			return;
		}
		
		StringBuffer filename = new StringBuffer(50);
		
		filename.append("Game").append(gameid).append('-');
		info.getBlackNames(filename);
		filename.append("-vs-");
		info.getWhiteNames(filename);
		filename.append(".sgf");
		
		String strFilename = filename.toString();
		strFilename = strFilename.replace(' ', '-');
		
		response.setContentType("application/x-go-sgf");
		response.setHeader("Content-Disposition", "attachment; filename=" + strFilename);
		
		PrintWriter writer = response.getWriter();
		writer.println(info.getStrippedSgf());
		writer.close();
	}
}
